package com.ms.pda.base

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.Bundle
import com.ms.architecture.status.ScanStateManager
import com.ms.architecture.utils.ScanUtil
import com.ms.pda.interf.OnDialogCallback
import com.ms.pda.utils.DialogUtil

abstract class ScanActivity : BaseActivity() {

    private var mScanStateManager: ScanStateManager? = null
    private var mLockScan: Boolean = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        lifecycle.addObserver(getScanStateManager())
    }

    private fun getScanStateManager(): ScanStateManager {
        if (mScanStateManager == null) {
            mScanStateManager = ScanStateManager(this)
        }
        return mScanStateManager!!
    }

    override fun initViews() {
        getScanStateManager().setReceiver(object : BroadcastReceiver() {
            override fun onReceive(context: Context?, intent: Intent?) {
                if (mLockScan) return
                intent?.let {
                    val data_string: String? =
                        ScanUtil.getValue(it, "com.symbol.datawedge.data_string")
                    data_string?.let {
                        println(data_string)
                        handleResult(data_string)
                    }
                }
            }
        })
    }

    abstract fun handleResult(code: String)


    private fun lockScan() {
        mLockScan = true
    }

    protected fun unlockScan() {
        mLockScan = false
    }

    /**
     * 本地校验码异常
     */
    fun checkCodeError(msg: String) {
        lockScan()
        DialogUtil.getTipPopupView(this, msg, object : OnDialogCallback {
            override fun onConfirm() {
                unlockScan()
            }

            override fun onCancel() {
                unlockScan()
            }
        })
    }

    fun checkCodeError(msg: String, callback: OnDialogCallback) {
        lockScan()
        DialogUtil.getTipPopupView(this, msg, callback)
    }

    fun checkCodeError(msg: String, hideCancel: Boolean, callback: OnDialogCallback) {
        lockScan()
        DialogUtil.getTipPopupView(this, msg, hideCancel, callback)
    }
}